package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.RenderUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.UuidUtil;
import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.FriendlyLink;
import cn.topcodes.tcsf.cms.domain.form.FriendlyLinkForm;
import cn.topcodes.tcsf.cms.domain.vo.FriendlyLinkVo;
import cn.topcodes.tcsf.cms.domain.vo.ImagePathVo;
import cn.topcodes.tcsf.cms.mapper.FriendlyLinkMapper;
import cn.topcodes.tcsf.cms.service.ConfigService;
import cn.topcodes.tcsf.cms.service.FriendlyLinkService;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 友情链接管理控制器
 *
 * @author Unicorn
 * @date 2017-12-25 21:34:53
 */
@Controller
@RequestMapping("/admin/cms/friendlylink")
public class FriendlyLinkController extends AdminController<FriendlyLink, FriendlyLinkVo, FriendlyLinkForm> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private FriendlyLinkService friendlyLinkService;

    @Autowired
    private FriendlyLinkMapper friendlyLinkMapper;

    @Override
    protected String getPageFolder() {
        return "/cms/friendlylink";
    }

    /**
     * 上传头像图片
     *
     * @param img
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "uploderLogo")
    public void uploderLogo(@RequestParam(required = true) String img,
                            HttpServletResponse response) throws IOException {
        String basePath = configService.getFileFolderPath();
        String imgPath = "UrlLogo/" + UuidUtil.getUUID();
        img = img.replaceAll("data:image/jpeg;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        byte[] b = decoder.decodeBuffer(img);
        for (int i = 0; i < b.length; ++i) {
            //调整异常数据
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        InputStream sbs = new ByteArrayInputStream(b);
        FileUtils.copyInputStreamToFile(sbs, new File(basePath + imgPath));

        ImagePathVo imagePathVo = new ImagePathVo();
        imagePathVo.setImagePath(imgPath);
        imagePathVo.setConcreteImagePath(OtherController.FILE_PATH + "?path=" + imgPath);
        RenderUtil.renderJson(imagePathVo, response);
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request, FriendlyLinkForm form, BindingResult result) {
        ValidationUtil.validate(result);
        FriendlyLink entity = this.form2Entity(form);
        Long maxSort = friendlyLinkMapper.findMaxSort();
        entity.setSort(maxSort == null ? 0 : maxSort.intValue() + 1);
        Long id = friendlyLinkService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request,
                                          @Valid @ApiParam("更新资源表单") FriendlyLinkForm form,
                                          BindingResult result) {
        ValidationUtil.validate(result);
        FriendlyLink t = this.form2Entity(form);
        FriendlyLink friendlyLink = friendlyLinkService.findOne(t.getId());
        t.setSort(friendlyLink.getSort());
        friendlyLinkService.update(t);
        return ApiResponseEntity.buildOK();
    }

    @Override
    protected void entity2VoDiff(FriendlyLink entity, FriendlyLinkVo vo) {
        if (StringUtil.isNotBlank(entity.getLogoUrl())) {
            vo.setLogoUrl(OtherController.FILE_PATH + "?path=" + entity.getLogoUrl());
        } else {
            vo.setLogoUrl(null);
        }
        vo.setLogo(entity.getLogoUrl());
        super.entity2VoDiff(entity, vo);
    }

    @Override
    public String update(@RequestParam Long id, HttpServletRequest request, Model model) {
        FriendlyLink entity = friendlyLinkService.findOne(id);
        FriendlyLinkVo friendlyLinkVo = new FriendlyLinkVo();
        friendlyLinkVo.setLogo(entity.getLogoUrl());
        friendlyLinkVo.setDescription(entity.getDescription());
        friendlyLinkVo.setName(entity.getName());
        friendlyLinkVo.setSort(entity.getSort());
        friendlyLinkVo.setUrl(entity.getUrl());
        friendlyLinkVo.setId(entity.getId());
        if (StringUtil.isNotBlank(entity.getLogoUrl())) {
            friendlyLinkVo.setLogoUrl(OtherController.FILE_PATH + "?path=" + entity.getLogoUrl());
        } else {
            friendlyLinkVo.setLogoUrl("");
        }
        model.addAttribute("entity", friendlyLinkVo);
        return this.getPageFolder() + "/update";
    }
}
